package org.demo.test;

import java.net.*;
import java.util.Enumeration;

/**
 * Created by tangwy on 2016/3/25.
 */
public class InetAddressDemo {
    public static void getAddress() {
        try {
            Enumeration<NetworkInterface> interfaceList = NetworkInterface.getNetworkInterfaces();
            if (interfaceList == null) {
                System.out.println("没有找到interface");
            }
            while (interfaceList.hasMoreElements()) {
                NetworkInterface networkInterface = interfaceList.nextElement();
                //获取网络接口名称
                System.out.println("InterfaceName:" + networkInterface.getName());
                Enumeration<InetAddress> addressList = networkInterface.getInetAddresses();
                if (addressList == null) {
                    System.out.println("没有找到IP地址");
                }
                while (addressList.hasMoreElements()){
                    InetAddress address=addressList.nextElement();
                    System.out.print(address instanceof Inet4Address?"V4":address instanceof Inet6Address?"V6":"?");
                    System.out.println("IP地址:" + address.getHostAddress());
                    System.out.println("主机名称:"+address.getHostName());
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public static void getAddress(String hostName){
        try {
            InetAddress[]addressesList=InetAddress.getAllByName(hostName);

            for(InetAddress address:addressesList){
                System.out.println("主机名称:"+address.getHostName()+"\t主机地址"+address.getHostAddress());
            }
        } catch (UnknownHostException e) {
            System.out.println("主机" + hostName + "没有找到");
            //e.printStackTrace();
        }
    }
}
